package com.lg.meng.observable.message;

import android.util.SparseArray;

import com.lg.meng.observable.BaseObservable;


/**
 * Author: xx
 * Date: 2019/4/7
 * Description: 消息管理
 */
public class MessageManager extends BaseObservable<MessageObserver> {
    private static MessageManager instance;

    private MessageManager() {

    }

    public static MessageManager getInstance() {
        if (instance == null) {
            synchronized (MessageManager.class) {
                if (instance == null) {
                    instance = new MessageManager();
                }
            }
        }
        return instance;
    }

    private final SparseArray<AppMessage> mMessages = new SparseArray<>();

    /**
     * 请求分发消息
     *
     * @param id
     * @param observer
     */
    public void subscribe(int id, MessageObserver observer) {
        AppMessage appMessage = mMessages.get(id);
        if (appMessage != null) {
            observer.onMessageUpdate(appMessage);
        }
    }

    /**
     * @param id 消息 id 用于取消一个消息
     */
    public void dispatchMessage(int id) {
        dispatchMessage(id, false);
    }

    public void dispatchMessage(int id, boolean remind) {
        dispatchMessage(new AppMessage(id, remind));
    }

    /**
     * 分发一个消息
     *
     * @param message 消息
     *                主线程处理
     */
    private void dispatchMessage(AppMessage message) {
        mMessages.put(message.getId(), message);
        for (MessageObserver observer : obs) {
            observer.onMessageUpdate(message);
        }
    }
}
